package com.quan.junit.generator;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.quan.common.utils.CommonUtils;

public class MySqlGenerator {

	private final static String dbUrl = "jdbc:mysql://localhost:3306/quan_luck_project?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8";
	private final static String driverClass = "com.mysql.cj.jdbc.Driver";
	private final static String username = "quan";
	private final static String password = "123456";

	// 输出目录（当前项目的根路径）
	private final static String OUTPUTDIR = System.getProperty("user.dir") + "\\generate";
	// VUE 页面输出目录
	private final static String VIEW_VUE_OUTPUTDIR = OUTPUTDIR + "\\view\\vue";
	// JS 文件目录
	private final static String VUE_API_JS_OUTPUTDIR = OUTPUTDIR + "\\view\\js";

	public static void main(String[] args) {

		// 系统模块
		List<String> tablesSystem = new ArrayList<String>();
		tablesSystem.add("tb_system_job");
		tablesSystem.add("tb_system_area");
		tablesSystem.add("tb_system_user_role");
		tablesSystem.add("tb_system_user");
		tablesSystem.add("tb_system_role_permission");
		tablesSystem.add("tb_system_role");
		tablesSystem.add("tb_system_permission");
		tablesSystem.add("tb_system_menu");
		tablesSystem.add("tb_system_log");
		tablesSystem.add("tb_system_settings");
		tablesSystem.add("tb_system_dict");
		tablesSystem.add("tb_system_dict_detail");
		tablesSystem.add("tb_system_file");
		String[] stringsSystem = new String[tablesSystem.size()];
		generator("com.quan", "system", tablesSystem.toArray(stringsSystem));

		// 微信公众号
		List<String> tablesWx = new ArrayList<String>();
		tablesWx.add("tb_weixin_menu");
		tablesWx.add("tb_weixin_oauth_user");
		tablesWx.add("tb_weixin_subscribe");
		
		String[] stringsWxs = new String[tablesWx.size()];
		generator("com.quan", "weixin", tablesWx.toArray(stringsWxs));


		// 其他模块
		// List<String> tablesMall = new ArrayList<String>();
		// tablesMall.add("tb_system_menu");
		// String[] stringsMall = new String[tablesMall.size()];
		// generator("com.quan", "mall", tablesMall.toArray(stringsMall));
	}

	/**
	 * 生成Mapper, Service, ServiceImpl, Controller, Vue, Js
	 * 按模块生成，包名+模块名称：com.quan+system
	 * 
	 * @param packageName 包名
	 * @param moduleName  模块名称
	 * @param tableNames  表名
	 */
	public static void generator(String packageName, String moduleName, String... tableNames) {
		// 代码生成器
		AutoGenerator autoGenerator = new AutoGenerator();

		// 全局配置
		GlobalConfig globalConfig = new GlobalConfig();
		// 输出路径
		globalConfig.setOutputDir(OUTPUTDIR);
		// 注释
		globalConfig.setAuthor("杨浩泉");
		// 是否打开输出目录
		globalConfig.setOpen(false);
		// 是否覆盖已有文件
		globalConfig.setFileOverride(true);
		// 开启 BaseResultMap
		globalConfig.setBaseResultMap(true);
		// 开启 baseColumnList
		globalConfig.setBaseColumnList(true);
		// service 命名方式，默认会再前面加（I），例如：%sBusiness 生成 UserBusiness
		globalConfig.setServiceName("%sService");
		autoGenerator.setGlobalConfig(globalConfig);

		// 数据源配置
		DataSourceConfig dataSourceConfig = new DataSourceConfig();
		dataSourceConfig.setUrl(dbUrl);
		dataSourceConfig.setDriverName(driverClass);
		dataSourceConfig.setUsername(username);
		dataSourceConfig.setPassword(password);
		dataSourceConfig.setTypeConvert(new MySqlTypeConvert() {
			// 自定义数据库表字段类型转换【可选】
			@Override
			public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
				// 转换类型
				// if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
				//	 return DbColumnType.BOOLEAN;
				// }
				return super.processTypeConvert(globalConfig, fieldType);
			}
		});
		autoGenerator.setDataSource(dataSourceConfig);

		// 包配置
		PackageConfig packageConfig = new PackageConfig();
		packageConfig.setModuleName(moduleName);
		packageConfig.setParent(packageName);
		packageConfig.setController("web.controller");
		autoGenerator.setPackageInfo(packageConfig);

		// 策略配置
		StrategyConfig strategyConfig = new StrategyConfig();
		strategyConfig.setTablePrefix("tb_");
		strategyConfig.setSuperControllerClass("com.quan.common.core.MyBaseController");
		strategyConfig.setSuperMapperClass("com.quan.common.core.MyBaseMapper");
		strategyConfig.setSuperServiceClass("com.quan.common.core.MyBaseService");
		strategyConfig.setSuperServiceImplClass("com.quan.common.core.MyBaseServiceImpl");

		strategyConfig.setEntityLombokModel(true);
		strategyConfig.setRestControllerStyle(true);

		strategyConfig.setNaming(NamingStrategy.underline_to_camel);
		strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);

		// 修改替换成你需要的表名，多个表名传数组
		strategyConfig.setInclude(tableNames);
		autoGenerator.setStrategy(strategyConfig);

		// 自定义模板
		List<FileOutConfig> focList = new ArrayList<FileOutConfig>();

		// Vue 模板
		focList.add(new FileOutConfig("/templates/view/view.index.vue.vm") {
			@Override
			public String outputFile(TableInfo tableInfo) {
				String deNamePath = CommonUtils.replaceUnderlineAndfirstToUpper(
						CommonUtils.upperCharToUnderLine(tableInfo.getEntityName()), "_", "\\");

				String path = VIEW_VUE_OUTPUTDIR + "/" + deNamePath + "/index.vue";
				File viewDir = new File(path).getParentFile();
				if (!viewDir.exists()) {
					viewDir.mkdirs();
				}
				return path;
			}
		});
		// JS 模板
		focList.add(new FileOutConfig("/templates/view/view.index.js.vm") {
			@Override
			public String outputFile(TableInfo tableInfo) {
				// String deNamePath = CommonUtils.replaceUnderlineAndfirstToUpper(CommonUtils.upperCharToUnderLine(tableInfo.getEntityName()), "_", "\\");

				String path = VUE_API_JS_OUTPUTDIR + File.separator + moduleName + File.separator
						+ tableInfo.getEntityName().toLowerCase().replace(moduleName, "") + ".js";
				File viewDir = new File(path).getParentFile();
				if (!viewDir.exists()) {
					viewDir.mkdirs();
				}
				return path;
			}
		});

		// 自定义配置
		InjectionConfig cfg = new InjectionConfig() {
			// 自定义属性注入:abc
			// 在.ftl(或者是.vm)模板中，通过${cfg.abc}获取属性
			@Override
			public void initMap() {
				Map<String, Object> map = new HashMap<>();
				map.put("abc", "模板属性注入");
				this.setMap(map);
			}
		};

		cfg.setFileOutConfigList(focList);
		autoGenerator.setCfg(cfg);

		// 生成
		autoGenerator.execute();

	}

}
